//
//  LeKeyFobService.h
//
//
//  Created by  on 2019/2/18.
//  Copyright © 2019 . All rights reserved.
//  连接的蓝牙设备操作

#import <Foundation/Foundation.h>
#import <CoreBluetooth/CoreBluetooth.h>
#import <UIKit/UIKit.h>
#import "SROTADefines.h"
#import "CADeviceInfo.h"
#import "CAHistoryData.h"
#import "CAHistoryDataSR03.h"

#import "CARingSDK.h"
#import "CASdkConstant.h"
#import "CAEcgData.h"
#import "CAEcgAlgorithmResults.h"
#import "CAnAlgGrandActivity.h"
#import "CAnAlgGrandActivity2.h"
#import "CAnAlgRealMeasure.h"
#import "CAnAlgRltExerData.h"
#import "CAPpgMeasureState.h"

/****************************************************************************/
/*						Service Characteristics								*/
/****************************************************************************/
//extern NSString *kSetDeviceAlertServiceUUIDString;
//extern NSString *kSetMobileAlertServiceUUIDString;
//extern NSString *kBatteryServiceUUIDString;
//extern NSString *serviceUUIDString;
//extern NSString *kSetDeviceAlertCharacteristicUUIDString;
//extern NSString *kSetMobileAlertCharacteristicUUIDString;
//extern NSString *kBatteryCharacteristicUUIDString;

/****************************************************************************/
/*								Protocol									*/
/****************************************************************************/
@class CABLeService;
@class CAPacket;

extern NSString * _Nonnull const CABluetoothManagerReceiveDevices;
extern NSString * _Nonnull const CABluetoothManagerConnectingToDevice;
extern NSString * _Nonnull const CABluetoothManagerConnectedToDevice;
extern NSString * _Nonnull const CABluetoothManagerDisconnectedFromDevice;
extern NSString * _Nonnull const CABluetoothManagerConnectionFailed;

extern NSString * _Nonnull const CAGenericServiceManagerDidReceiveValue;
extern NSString * _Nonnull const CAGenericServiceManagerDidSendValue;
extern NSString * _Nonnull const CAGenericServiceManagerReadError;
extern NSString * _Nonnull const CAGenericServiceManagerWriteError;


extern NSString * _Nullable const CASERVICE_UUID_DATA; // 扫描过滤的uuid

//extern NSString * const serviceUUIDString;



@protocol StLeKeyFobProtocol<NSObject>
@required
// 电池服务初始化完毕
- (void)stkeyFobServiceBatteryReady;

- (void) stkeyFobServiceDidChangeStatus:(CABLeService * _Nonnull)service;
- (void) stkeyFobServiceDidConnectPeripheral:(CABLeService * _Nonnull)service;
- (void) stkeyFobServiceDidDisconnectPeripheral:(CABLeService * _Nonnull)service;
- (void) stkeyFobServiceDidReadRSSI:(CABLeService * _Nonnull)service;
- (void) stkeyFobServiceDidReset;

- (void) stkeyFobServiceDidFailConnectPeripheral:(CBPeripheral* _Nonnull)peripheral Error:(NSError * _Nonnull)error;




/// 实时hrv
/// @param hrv hrv
- (void)stkeyFobServiceRealtimeHRV:(NSNumber *_Nullable)hrv BloodOxygen:(NSNumber *_Nullable)bloodOxygen HeartRate:(NSNumber *_Nullable)hr Status:(REALTIME_STATUS)status;


/// 实时计步
/// @param steps 计步
//- (void)stkeyFobServiceRealtimeSteps:(NSNumber *)steps; // 废弃

/// 实时计步
/// @param steps 计步
- (void)stkeyFobServiceRealtimeSteps:(NSNumber *_Nonnull)steps IsDeviceFix:(BOOL)isDeviceFixed;

/// 实时体温
/// @param temperature 体温
- (void)stkeyFobServiceRealtimeTemperaure:(NSNumber *_Nonnull)temperature;


// 回调设备信息
- (void)stkeyFobServiceDeviceInfo:(CADeviceInfo *_Nonnull)devInfo;


/// 读写数据主特征准备完毕
- (void) stkeyFobServiceDidReadyForReadWrite:(CABLeService *_Nonnull)service;


/// 电量回调
/// @param batteryLevel 电量
/// @param isCharging 是否充电
- (void) stkeyFobServiceBatteryLevel:(NSInteger)batteryLevel IsCharging:(BOOL)isCharging Voltage:(float)vol;

- (void) stkeyFobServiceSN:(NSString *_Nonnull)sn OriginSNData:(NSData *_Nonnull)sndata;
- (void) stkeyFobServiceHistoryTimeout;
- (void) stkeyFobServiceHistoryCount:(NSInteger)count;
- (void) stkeyFobServiceHistoryData:(CAHistoryData *_Nullable)hisData IsComplete:(BOOL)isComplete;

/// 设备信息5
/// - Parameters:
///   - durations: 心率 体温测量时长
///   - pd_threshold: pd阈值
///   - pd_range_1:pd波动 范围1
///   - pd_range_2: pd采样波动 范围2
-(void)stkeyFobServiceHrMeasuDuration:(NSInteger)durations PD_THRESHOLD:(uint32_t)pd_threshold PD_RANGE_1:(uint32_t)pd_range_1 PD_RANGE_2:(uint32_t)pd_range_2;


/// 回调计步阈值
/// - Parameter threshold: 阈值
-(void)stkeyFobServiceCountThreshold:(uint8_t)threshold;

// sr03设备的历史回调
- (void) stkeyFobServiceHistorySR03Data:(CAHistoryDataSR03 * _Nullable)sr03HisData IsComplete:(BOOL)isComplete;


//- (void) stkeyFobServiceSendCmdExcute:(uint8_t)cmd Succ:(BOOL)isSuccess; // 废弃
//
//- (void) stkeyFobServiceSendCmdExcute:(uint8_t)cmd Succ:(BOOL)isSuccess Reason:(CMD_EXECTE_ERROR_REASON)reason;


- (void) stkeyFobServiceSendCmdExcute:(uint8_t)cmd Succ:(BOOL)isSuccess Reason:(CA_CMD_EXECTE_ERROR_REASON)reason Data:(NSData *_Nonnull)originData;


///
/// @param isSosOpen sos
/// @param doubleTapTimes 双击
/// @param singleTapInterval 单击
/// @param tapDetectionThreshold 单击
/// @param doubleTapEffectStartTime 双击
/// @param doubleTapEffectEndTime 双击
/// @param isBinded 是否绑定
- (void) stkeyFobService:(BOOL)isSosOpen
          DoubleTapTimes:(uint8_t)doubleTapTimes
       SingleTapInterval:(uint8_t)singleTapInterval TapDetectionThreshold:(uint8_t)tapDetectionThreshold
DoubleTapEffectStartTime:(uint8_t)doubleTapEffectStartTime DoubleTapEffectEndTime:(uint8_t)doubleTapEffectEndTime Isbinded:(BOOL)isBinded;

-(void)stkeyFobServiceIsBinded:(BOOL)isBinded;

- (void) stkeyFobServiceSOShappen;
- (void)stkeyFobServiceSOSData:(float)temperature HeartRate:(NSInteger)hr BloodOxygen:(NSInteger)bloodOxygen;

// 回调ecg波形, ecgObj.isAlgorithData = NO为原始波形
- (void)stkeyFobServiceEcg:(CAEcgData *_Nullable)ecgObj;

- (void)stkeyFobServiceEcgAndPPg:(CAEcgData *_Nullable)ecgPpgObj;

// 回调ecg算法结果
- (void)stkeyFobServiceEcgResult:(CAEcgAlgorithmResults *_Nullable)ecgResult;

- (void)stkeyFobServiceEcgLeadOn:(BOOL)leadOn;
/*   AES */


/// 设备上报R1密文
/// - Parameter r1: 密文
- (void)stkeyFobServiceAESRecvR1:(NSData *_Nullable)r1;

/// 设备上报认证最后结果
/// - Parameter isAuthed: YES = auth pass
- (void)stkeyFobServiceAESAuthResult:(BOOL)isAuthed;

/*   AES */

/* NALG */
-(void)stkeyFobServiceUsrInfoFromoDev:(NSUInteger)gender
                Age:(NSUInteger)ageYear
              Height:(NSUInteger)height
             Weight:(NSUInteger)weight;

// 上报最后一条活动
-(void)stkeyFobServiceLastActivity:(CAnAlgGrandActivity *_Nullable)activity;
-(void)stkeyFobServiceLastActivity2:(CAnAlgGrandActivity2 *_Nullable)activity2;

-(void)stkeyFobServiceCSEMRealMeasu:(CAnAlgRealMeasure *_Nullable)realMeasurData;

// 活动+游泳+sleep 历史 个数
-(void)stkeyFobServiceHisCntOfActivityAndSwimAndSleep:(NSUInteger)count MinUUid:(uint32_t)minUUid MaxUUid:(uint32_t)maxUUid;

// 上报测量时长,测量间隔
-(void)stkeyFobServiceCSEMDevMeaDuration:(CACS_DEV_MEA_DURA_AND_TM_TYPE)meaType
                     MeaDuraofNoSlepPerd:(uint32_t)meaduraNoSleep MeaIntervOfNoSlepPerd:(uint32_t)meaIntervNoSleep
                     MeaDuraofInSlepPerd:(uint32_t)meaduraInSleep MeaIntervInNoSlepPerd:(uint32_t)meaIntervInSleep;

-(void)stkeyFobServiceCSEMalgorithmType:(uint8_t)algorithmType;

// 上报csem的历史数据
-(void)stkeyFobServiceCsemDeviceMeasurData:(id<CANalgProtocal>_Nullable)dataObj;

// 实时上报锻炼活动数据
-(void)stkeyFobServiceCsemRealtimeWorkoutData:(CAnAlgRltExerData *_Nullable)csemExerRltData;

-(void)stkeyFobServiceLedStateReport:(BOOL)on Led:(uint8_t)led Current:(uint8_t)current AutoDim:(uint8_t)autoDim Freq:(uint8_t)freq;

-(void)stkeyFobServicePPGState:(CAPpgMeasureState *_Nullable)stateObj;

-(void)stkeyFobServiceLedPPgDataRep:(NSMutableArray<NSNumber *> *_Nullable)dataArry;


@end

// ota 协议
@protocol StLeKeyOTAProtocol<NSObject>
@required
// ota 的数据返回
-(void)srOtaDidReceiveValue:(CBCharacteristic *_Nullable)characteristic;


@end

/****************************************************************************/
/*						Temperature Alarm service.                          */
/****************************************************************************/
@interface CABLeService : NSObject


/* Querying Sensor */
@property (readonly) CBPeripheral * _Nonnull peripheral;
@property (assign, readonly) CGFloat battery;
@property (assign, nonatomic) BOOL isAlerting;
@property (strong, nonatomic)NSNumber * _Nullable rssi; // 信号强度 负数
@property (assign, nonatomic) BOOL isManualDisconnect;      //标记用户手动断开
@property (assign, nonatomic) BOOL isExceptional;           //异常断开
@property (assign, nonatomic) NSInteger reconnectCounts;    //重连次数
@property (strong, nonatomic)NSString * _Nullable advDataLocalName;    //外设本地名称
@property (strong, nonatomic)NSString * _Nullable macAddress;

@property (assign, nonatomic)uint16_t cid;

@property(assign, nonatomic, readonly) int suotaVersion;
@property(assign, nonatomic, readonly) int suotaMtu;
@property(assign, nonatomic, readonly) int suotaPatchDataSize;
@property(assign, nonatomic, readonly) int suotaL2CapPsm;

@property(strong, nonatomic) CAPacket * _Nullable packetObj;  //封包 解包

@property(assign, nonatomic)CA_DEV_COLOR deviceColor; // 设备颜色
@property(assign, nonatomic)int deviceSize;  // 设备尺寸

@property(assign, nonatomic)CA_MAIN_CHIP_TYPE mainChipType; // 主芯片型号
@property(assign, nonatomic)NSUInteger deviceGeneration;  // 迭代版本

@property(assign, nonatomic)BOOL needOemAuth; //是否需要oem厂家认证
@property(strong, nonatomic)NSString * _Nullable snString;
@property(strong, nonatomic)NSData * _Nullable authSnData; // 认证使用sn data
@property(strong, nonatomic)NSString * _Nullable softWareVersion;

@property(assign, nonatomic) BOOL hasBeenAuth; // 标记已认证过,无论是否通过认证都是YES

@property(strong, nonatomic)NSNumber * _Nullable isWirenessCharge; //是否无线充电

@property(assign, nonatomic)BOOL isBinded;
@property(assign, nonatomic)BOOL isSupportSportMode;
@property(strong, nonatomic)NSNumber * _Nullable chargeType;// 充电模式

@property(strong, nonatomic)NSNumber * _Nullable scanIsCharge, * _Nullable scanBatteryLevel;

@property(assign, nonatomic)BOOL isSupportEcg;
@property(assign, nonatomic)CA_RING_PROJECT_ID projectId;
@property(assign, nonatomic)BOOL isCharging;

- (instancetype _Nullable ) initWithPeripheral:(CBPeripheral *_Nonnull)peripheral;

- (id _Nullable ) initWithPeripheral:(CBPeripheral *_Nullable)peripheral controller:(id<StLeKeyFobProtocol>_Nullable)delegate;
- (void) reset;
- (void) start;
- (void) stopRssiTimer;


/// Used for external scanning to determine how to parse broadcast packets.
+(NSArray<NSArray<NSNumber *> * > *_Nonnull)cidArray;


-(void)setAdvData:(NSDictionary *_Nonnull)advertisementData;

-(BOOL)isConnected;

/* sdk 不开放方法 */

-(id<StLeKeyFobProtocol>_Nonnull)perpheralDelegate;
-(void)setPerpheralDelegate:(id<StLeKeyFobProtocol>_Nullable)delegate;

/// 获取心率血氧开关
/// @param isStart isStart = NO 关闭  isStart = yes 开启
//-(void)deviceOxygenAndHrv:(BOOL)isStart;
-(void)deviceOxygenAndHrvBoth:(BOOL)both IsOpen:(BOOL)isStart;

-(void)cmdDeviceShutDown;
-(void)cmdDeviceReboot;
-(void)cmdDeviceBattery;
-(void)cmdSn;
-(void)cmdHistoryCount; // 获取历史个数 流程开始
-(void)cmdHistoryData; // 获取历史

-(void)cmdClearHistory;
-(void)cmdLedMeasure:(BOOL)on LedColor:(uint8_t)ledColor AutoAdjBri:(BOOL)autoAdjBri Current:(uint8_t)current SampleRate:(uint8_t)sampleRate;

-(void)cmdDevInfo;
-(void)cmdTimeSync:(NSDate *_Nonnull)date; // 时间同步
-(void)cmdGetSteps;
-(void)cmdGetTemperature;
-(void)cmdFactoryReset;
-(void)cmdBindeDevice:(BOOL)bind; //绑定解绑
-(void)cmdOEMSwitch:(BOOL)on;
-(void)cmdGetDevInfoFive;
-(void)cmdSetMeasureDuration:(NSInteger)durations;

// 开始oem认证
-(void)cmdStartOemAuth;

// 发送解密后的明文
-(void)cmdOEMSendR2:(NSData *_Nonnull)r2;

/// 血氧测量设置
/// @param startHor 开始 时
/// @param startMin 开始 时分
/// @param startSecond 开始 秒
/// @param endHor 结束 时
/// @param endMin 结束 分
/// @param endSec 结束 秒
/// @param interval 间隔 单位:分钟
-(BOOL)cmdSettingOxygenMeasure:(NSUInteger)startHor StartMin:(NSUInteger)startMin StartSec:(NSUInteger)startSecond Endhor:(NSUInteger)endHor EndMin:(NSUInteger)endMin EndSec:(NSUInteger)endSec Interval:(NSUInteger)interval IsOn:(BOOL)isOn;

-(void)cmdSettingHeartRateMeasurInterval:(NSUInteger)hrInterval SkinTemperatureInterval:(NSUInteger)skinTemperatureInterval IsOn:(BOOL)isOn;

-(void)cmdSettingSportMode:(NSUInteger)startHor StartMin:(NSUInteger)startMin
                  StartSec:(NSUInteger)startSecond Endhor:(NSUInteger)endHor
                    EndMin:(NSUInteger)endMin EndSec:(NSUInteger)endSec
                HrIntreval:(NSUInteger)hrInterval SkinTemperatureInterval:(NSUInteger)skinTemperatureInterval
                  BloodOxygenInterval:(NSUInteger)oxygeninterval
                      IsOn:(BOOL)isOn;

//-(void)cmdSOSSettingDoubleTapTimes:(uint8_t)doubleTapTimes
//    SingleTapInterval:(uint8_t)singleTapInterval TapDetectionThreshold:(uint8_t)tapDetectionThreshold
//          DoubleTapEffectStartTime:(uint8_t)doubleTapEffectStartTime DoubleTapEffectEndTime:(uint8_t)doubleTapEffectEndTime Open:(BOOL)sosOpen;
///
/// @param start 开关
/// @param valInterval 设备取值间隔 秒
/// @param durationMIn 设备持续时间 分钟
-(void)cmdSportMode:(BOOL)start ValueINterval:(uint16_t)valInterval Duration:(uint16_t)durationMIn WorkType:(CA_WORKOUT_TYPE)workoutType;


- (void) otaWriteValueWithoutResponse:(CBUUID*_Nonnull)serviceUUID characteristicUUID:(CBUUID*_Nonnull)characteristicUUID data:(NSData*_Nonnull)data;

- (void) otaWriteValue:(CBUUID*_Nonnull)serviceUUID characteristicUUID:(CBUUID*_Nonnull)characteristicUUID data:(NSData*_Nonnull)data;

- (void) setNotifications:(CBUUID*_Nonnull)serviceUUID characteristicUUID:(CBUUID*_Nonnull)characteristicUUID enable:(BOOL)enable;

-(void)cmdEcgAndPpgMeasure:(BOOL)on;

-(void)cmdECGMeasure:(BOOL)on SampleRate:(uint16_t)sampleRate InnerClockSource:(uint8_t)clockSource EcgPgaGain:(uint8_t)ecgPgaGain DispSrc:(BOOL)isFilterWave;

-(void)cmdSetStepCountingThreshold:(uint8_t)threshold;
-(BOOL)cmdGetLastActivity_2;
// 改广播名
-(BOOL)cmdModifyBRcastName:(NSString *_Nonnull)name HideMac:(BOOL)hideMac;

/* CSEM */

// 设置用户信息
//性别: 0 男性、1 女性
//年龄: 范围 1-115
//身高: 单位 mm，范围 1200-3000
//体重: 单位 kg，范围 30-200
-(BOOL)cmdSetUsrInfoToDev:(NSUInteger)gender Age:(NSUInteger)ageYear Height:(NSUInteger)height Weight:(NSUInteger)weight;

-(BOOL)cmdGetUsrInfoToDev;

-(BOOL)cmdGetLastActivity;

-(BOOL)cmdCleanActivityHistory;

// 获取活动历史 数量
-(BOOL)cmdGetHistoryCntOfActvtyDtctnAndSwimAndSlepHist;

///// Get all activity detection/exercise/new history data/temperature history data/sleep data
/////
//-(BOOL)cmdGetHistoryDataOfActvtyDtctnAndSwimAndSlepHist;


/// Get part of activity detection/exercise/new history data/temperature history data/sleep data
///
/// - Parameter maxUUid:The end uuid of the data to be retrieved
-(BOOL)cmdGetHistoryDataOfActvtyDtctnAndSwimAndSlepHistMax:(uint32_t)maxUUid;


-(BOOL)cmdSetCsemMea:(uint32_t)type IsSet:(BOOL)isSet DuraNoSleep:(uint32_t)meaDuraNoSleep IntervNosleep:(uint32_t)meaIntervNoSleep DuraInSleep:(uint32_t)meaduraInSleep IntervInsleep:(uint32_t)meaIntervInSleep;

-(BOOL)cmdSetCSEMexercise:(uint8_t)subCmd ExerciseType:(uint8_t)execType PoolSize:(uint8_t)sizeType HeartrateStorageInterval:(uint16_t)hrStoreInterv DurationMins:(uint16_t)duraMins
;

-(BOOL)cmdSetCSEMexerciseRealReportSwitch:(BOOL)on;

-(BOOL)cmdDeviceAlgorithm:(BOOL)isSet Type:(uint8_t)algorithmType;

/* CSEM */


/* sdk 不开放方法 */

+ (CBUUID*_Nonnull) SPOTA_SERVICE_CBUUID;

+ (CBUUID*_Nonnull) SPOTA_MEM_DEV_CBUUID ;

+ (CBUUID*_Nonnull) SPOTA_GPIO_MAP_CBUUID ;

+ (CBUUID*_Nonnull) SPOTA_MEM_INFO_CBUUID ;

+ (CBUUID*_Nonnull) SPOTA_PATCH_LEN_CBUUID ;

+ (CBUUID*_Nonnull) SPOTA_PATCH_DATA_CBUUID ;

+ (CBUUID*_Nonnull) SPOTA_SERV_STATUS_CBUUID ;

+ (CBUUID*_Nonnull) SUOTA_VERSION_CBUUID ;

+ (CBUUID*_Nonnull) SUOTA_PATCH_DATA_CHAR_SIZE_CBUUID ;

+ (CBUUID*_Nonnull) SUOTA_MTU_CBUUID ;

+ (CBUUID*_Nonnull) SUOTA_L2CAP_PSM_CBUUID ;



@end
